<?php
require_once 'config.inc.php';

header('Content-type: application/json');

if (empty($_POST['Key_ID']) or empty($_POST['Key_Ver_Code']) or !is_numeric($_POST['Key_ID']) or !ctype_alnum($_POST['Key_Ver_Code'])) {
  die(json_encode(array('error' => 'API info is missing or incorrectly formatted.')));
}

$characters = simplexml_load_file('https://api.eveonline.com/account/APIKeyInfo.xml.aspx?keyID=' . $_POST['Key_ID'] . '&Vcode=' . $_POST['Key_Ver_Code'])
  or die(json_encode(array('error' => 'Error connecting to EVE API server.')));

if (isset($characters->error) and substr((string) $characters->error->attributes()->code, 0, 1) == 2) {
  die(json_encode(array('error' => 'Authentication failed for this key.')));
}

if (!isset($characters->result->key->rowset->row)) {
  die(json_encode(array('error' => 'The character list could not be gathered for this key at this time.')));
}

if (((int) $characters->result->key->attributes()->accessMask & $config['Minimum Access Mask']) != $config['Minimum Access Mask']) {
  die(json_encode(array('error' => 'This key does not allow the minimum access options chosen by your admin. Use the link on the registration page to create a key with the correct access level.')));
}

if ($config['Account Key Required'] and (string) $characters->result->key->attributes()->type != 'Account') {
  die(json_encode(array('error' => 'Your admin requires an account key, but this is a character-specific key.  Choose All under Character when creating.')));
}

foreach($characters->result->key->rowset->row as $row) {
  if (array_key_exists((string) $row->attributes()->corporationID, $config['Corps'])) {
    $response['names'][] = (string) $row->attributes()->characterName;
  }
}
if (empty($response['names'])) {
  die(json_encode(array('error' => 'No characters in configured corps. were found with this key.')));
}

if ((string) $characters->result->key->attributes()->expires != '') {
  $response['warnings'][] = <<<EOL
Your key will work, but as it has a set expiration date, you will lose your access when it expires. If you want to correct this, you don't need to make a new key.  You can simply update the one you already made to not expire.
EOL;
}

echo json_encode($response);
?>